<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            text-align: center;
        }

        h1 {
            margin-top: 20px;
        }

        .box {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }

        .boxs {
            width: 100%;
            height: 200px;
            line-height: 200px;
            margin-bottom: 20px;
            opacity: 0;
            transition: opacity 0.8s ease-in;
            background-color: aquamarine;
        }

        .boxs.loaded {
            opacity: 1;
        }
    </style>
</head>

<body>
    <h1>Lazy Loading Images</h1>
    <div class="box">
        <div class="box1 boxs">1</div>
        <div class="box2 boxs">2</div>
        <div class="box3 boxs">3</div>
        <div class="box4 boxs">4</div>
        <div class="box5 boxs">5</div>
    </div>

    <script>
        // 监听滚动事件
        window.addEventListener('scroll', function () {
            // 获取所有boxs
            const boxs = document.querySelectorAll('.boxs')
            const windowHeight = window.innerHeight;//获取视口高度

            // 遍历所有boxs
            boxs.forEach(item => {
                const rect = item.getBoundingClientRect();//获取boxs相对于视口的位置

                if (rect.top < windowHeight) {
                    // 此时box进入视口
                    item.classList.add('loaded')// 添加 loaded 类，触发渐显效果
                }
            });
        });
        // 页面初始加载时通过 DOMContentLoaded 事件立即检查是否有div已经在视窗中
        document.addEventListener('DOMContentLoaded', function () {
            window.dispatchEvent(new Event('scroll'))
        })
    </script>
</body>

</html>